package wk.demo.bean;
import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import android.os.Handler;
import android.widget.Toast;

/**
 * 程序中任何一个activity处于后台时(onStope)都将触发提醒。
 * 顶层activity中onStope方法被执行，则认为程序处于后台。
 */
public class MyAppLifecycleHandler implements Application.ActivityLifecycleCallbacks {
    private int started = 0;
    private int stopped = 0;
    private String lastActivitName ;
    private boolean flag = true;

    public MyAppLifecycleHandler(String name){
        lastActivitName= name ;
    }


    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {  }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {  }

    @Override
    public void onActivityResumed(Activity activity) {

    }

    @Override
    public void onActivityPaused(Activity activity) {  }


    @Override
    public void onActivityStarted(Activity activity) {
        ++started;
    }


    @Override
    public void onActivityStopped(final Activity activity) {
        ++stopped;

        if (!isApplicationInBackground()){
            return;
        }

        flag = true;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if ( flag ) {
                    Toast.makeText(activity, "WkPlayer被切换至后台", Toast.LENGTH_SHORT).show();
                }
            }
        } ,500) ;

    }

    @Override
    public void onActivityDestroyed(Activity activity) {
        if (lastActivitName.contains(activity.getClass().getSimpleName())) {
            flag = false;
        }
    }

    private boolean isApplicationInBackground() {
        return started == stopped;
    }

}
